//
//  AWTabBar.swift
//  WeiBo
//
//  Created by AaronWei on 2017/6/4.
//  Copyright © 2017年 AaronWei. All rights reserved.
//

import UIKit

protocol AWTabBarDelegate: NSObjectProtocol {
    
    func composeOperation()
    
}

class AWTabBar: UITabBar {
    
    var callBack: (()->())?
    
    weak var tabBarDelegate: AWTabBarDelegate?
    
    private lazy var composeButton: UIButton = {
    
        let button = UIButton()
        
        button.addTarget(self, action: #selector(composeButtonDidClicked), for: .touchUpInside)
        
        button.setBackgroundImage(#imageLiteral(resourceName: "tabbar_compose_button"), for: .normal)
        
        button.setBackgroundImage(#imageLiteral(resourceName: "tabbar_compose_button_highlighted"), for: .highlighted)
        
        button.setImage(#imageLiteral(resourceName: "tabbar_compose_icon_add"), for: .normal)
        
        button.setImage(#imageLiteral(resourceName: "tabbar_compose_icon_add_highlighted"), for: .highlighted)
        
        button.sizeToFit()
        
        return button
        
    }()

    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setupUI()
        
    }
    
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        
        setupUI()
        
    }
    
    private func setupUI() {
        
        addSubview(composeButton)
        
        backgroundImage = #imageLiteral(resourceName: "tabbar_background")
        
    }
    
    @objc private func composeButtonDidClicked() {
        
        tabBarDelegate?.composeOperation()
        
        callBack?()
        
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        
        composeButton.centerX = width * 0.5
        
        composeButton.centerY = height * 0.5
        
        let buttonWidth = width / 5
        
        var index = 0
        
        for subView in subviews {
            
            if subView.isKind(of: NSClassFromString("UITabBarButton")!) {
                
                subView.width = buttonWidth
                
                subView.x = CGFloat(index) * buttonWidth
                
                index += 1
                
                if index == 2 {
                    
                    index += 1
                    
                }
                
            }
            
        }
        
    }
    
}
